<!--
  文件名: login.vue
  描述: 这是一个登录界面，参考登录界面为腾讯云+百度智能云登录界面
  作者: 白紫铜
  创建日期: 2024-3-08
-->
<template>
<div id="login" style="text-align: center ;background-color: #000000">
  <el-container class="LoginPlace">
    <el-aside class="aside" width="600px">
      <div style="text-align: right">
        <router-link to="./register">
        <el-button class="register-button">注册</el-button>
        </router-link>
      </div>
      <div style="margin-bottom: 20px"/>
      <el-button
          type="text"
          class="el-telephone-button"
          :class="{'active-button': isEmailLinkAlive}"
          @click="ShowEmailLoginPlace"
      >邮箱验证登录</el-button>
      <span class="link-separator"></span>
      <el-button
          type="text"
          class="el-username-button"
          :class="{'active-button': isUsernameLinkAlive}"
          @click="ShowUsernameLoginPlace"
      >用户名密码登录</el-button>
      <div style="margin-bottom: 50px"/>
      <div v-show="ShowUsernameForm"><!--v-show设置表单显示与隐藏-->
        <el-form :model="form" ref="UsernameLoginForm">
      <el-input
          class="username"
        v-model="username"
        placeholder="请输入用户名"
        clearable></el-input>
      <div style="margin-bottom: 20px"/>
      <el-input
          class="password"
        v-model="password"
        type="password"
          show-password
        placeholder="请输入密码"
        clearable></el-input>
      <div style="margin-bottom: 20px"/>
      <el-button class="login-button" @click="handleUsernameAndPasswordLogin" @keyup.enter="handleUsernameAndPasswordLogin">登录</el-button>
        </el-form>
      </div>
      <div v-show="ShowEmailForm"><!--v-show设置表单显示与隐藏-->
        <el-form :model="form" ref="EmailLoginForm">
          <el-input
              class="email"
              v-model="email"
              placeholder="请输入邮箱"
              clearable></el-input>
          <div style="margin-bottom: 20px"/>
          <el-input
              class="captcha"
              v-model="captcha"
              placeholder="请输入验证码"
              clearable></el-input>
          <span class="link-separator"></span>
          <el-button
              class="captcha-button"
              @click="handleGetCaptcha"
              :disabled="waitingForCaptcha"
              :class="{'waiting': waitingForCaptcha}">
            {{waitingForCaptcha ? `${countdown}s后重新获取`:"获取验证码"}}</el-button>
          <div style="margin-bottom: 20px"/>
          <el-button class="login-button" @click="handleEmailLogin" @keyup.enter="handleEmailLogin">登录</el-button>
        </el-form>
      </div>
    </el-aside>
    <el-main class="main"><img style="width: 700px; height: 620px" :src="backgroundUrl" alt="background" /></el-main>
  </el-container>
</div>
</template>
<script>
import url from "@/assets/logo(1).png";
import background from "@/assets/background.png";
import axios from "axios";

export default {
  name : 'LoginView',
  data(){
    return{
      username:"",
      password:"",
      email:"",
      captcha:"",
      correctCaptcha:"",
      ShowUsernameForm:false,//控制表单显示和隐藏
      ShowEmailForm:true,
      form:{},//添加表单数据
      isUsernameLinkAlive:false,//新增状态，表示账号密码登录链接是否为激活状态
      isEmailLinkAlive:true,
      isLoginFormValid: false, // 控制登录表单是否有效
      isEmailValid: false, // 控制手机号格式是否有效
      waitingForCaptcha:false,
      countdown:60,
    }

  },
  computed: {
    url() {
      return url
    },
    backgroundUrl() {
      return background; // Add a computed property for the background image
    },
  },
  mounted() {
    document
        .querySelector("body")
        .setAttribute("style","background-color:#FAFAFA")
  },
  created() {
    const isAuthenticated=localStorage.getItem('token')
    if(isAuthenticated){
      this.$message("您已登录")
      this.$router.push({name:'HomePage'})
    }
  },
  methods:{
    ShowUsernameLoginPlace(){
      this.ShowUsernameForm=true       //显示当前链接表单
      this.ShowEmailForm=false     //关闭另一个链接表单
      this.isUsernameLinkAlive = true; // 点击链接时激活状态
      this.isEmailLinkAlive=false  //关闭另一个链接的激活状态
      this.email=""
      this.captcha=""
    },
    ShowEmailLoginPlace(){         //同上
      this.ShowEmailForm=true
      this.ShowUsernameForm=false
      this.isUsernameLinkAlive=false
      this.isEmailLinkAlive=true
      this.username=""
      this.password=""
    },
    handleUsernameAndPasswordLogin() {
      if (this.isLoginFormValid) {
        //发送登录请求
        axios.post('http://localhost:1145/login',{
          username:this.username,
          password:this.password,
          loginType:'username_password',
        },).then(response=>{
          console.log(response.data)
          //接收后端返回的令牌
          const token=response.data
          //保存令牌
          localStorage.setItem('token',token)
          console.log(token)
          this.$message.success("登陆成功")
          this.$router.push({name:"HomePage"})
          window.location.reload()
        }).catch(error=>{
          console.log("登陆失败:",error)
          this.$message.error("登陆失败，请检查用户名或密码是否正确")
        })
      } else {
        // 提示用户填写完整表单
        this.$message.error("请填写完整的登录信息");
      }
    },
    handleEmailLogin() {
      if (this.isLoginFormValid) {
        axios.post('http://localhost:1145/verifyCaptcha',{
          email: this.email,
          captcha: this.captcha,
        }).then(response=>{
          console.log(response.data)
          axios.post('http://localhost:1145/login',{
            email:this.email,
            captcha:this.captcha,
            loginType:"email_captcha",
          }).then(response=>{
            console.log(response.data)
            //接收后端返回的令牌
            const token=response.data
            //保存令牌
            localStorage.setItem('token',token)
            localStorage.setItem('username',this.username)

            this.$message.success("登陆成功")
            this.$router.push({name:"HomePage"})
            window.location.reload()
          }).catch(error=>{
            console.log("登陆失败:",error)
            this.$message.error("登陆失败，请检查手机号或验证码是否正确")
          }).catch(error => {
            this.$message.error("验证码错误，请重新输入"+error);
          });
        })

      } else {
        // 提示用户填写完整表单
        this.$message.error("请填写完整的登录信息");
      }
    },
    handleGetCaptcha(){
      if(this.isEmailValid){
        const smsRequest={
          email: this.email,
        }
        axios.post('http://localhost:1145/sendEmail',smsRequest)
            .then(response=>{
              console.log(response.data);
            }).catch(error=>{
          console.error('ERROR:',error)
        })
        this.startCountdown()
        console.log("Perform captcha")

      }
      else {
        this.$message.error("请填写11位手机号码")
      }
    },
    // 根据表单内容验证表单是否有效
    validateLoginForm() {
      if (this.ShowUsernameForm) {
        // 如果是用户名密码登录
        this.isLoginFormValid = !!this.username && !!this.password;
      } else if (this.ShowEmailForm) {
        // 如果是手机号登录
        this.isLoginFormValid = !!this.email && !!this.captcha;
      }
    },
    validateEmail(){
      const phoneNumberPattern=/\S+@\S+\.\S+/; //定义手机号格式的正则表达式，11位数字
      this.isEmailValid=phoneNumberPattern.test(this.email);
    },
    startCountdown(){
      this.waitingForCaptcha=true
      let timer=setInterval(()=>{
        if(this.countdown>0){
          this.countdown--;
        }
        else {
          clearInterval(timer)
          this.resetCaptchaButton();
        }
      },1000)
    },
    resetCaptchaButton(){
      this.waitingForCaptcha=false
      this.countdown=60
    },
  },
  watch: {
    // 监听输入框内容变化，动态验证表单
    username() {
      this.validateLoginForm();
    },
    password() {
      this.validateLoginForm();
    },
    email() {
      this.validateLoginForm();
      this.validateEmail();
    },
    captcha() {
      this.validateLoginForm();
    },
  },
}
</script>

<style scoped>
.aside{
  background-color: #ffffff;
  height: 550px;
  width: 400px;
  margin-left: 300px;
  margin-top: 15px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 添加阴影 */
}
.el-telephone-button{
  font-size: 16px;
  color: #000000;
  transition: color 0.3s ease;
}
.el-username-button{
  font-size: 16px;
  color: #000000;
  transition: color 0.3s ease;
}
.el-username-button:hover,
.el-telephone-button:hover{
  color: #606266;
}
.link-separator{
  margin: 0 10px;
}
.register-button{
  font-size: 12px;
  clip-path: polygon(0% 0%,100% 0%,100% 100%,30% 100%);
  border-radius: 0;
  border: none;
  width: 80px;
  height: 40px;
  background-color : #303133;
  transition: color 0.3s ease,background-color 0.3s ease;
  color: #ffffff
}
.register-button:hover{
  background-color: #606266;
  color: #ffffff;
}
.active-button {
  position: relative;
  color: #303133; /* 修改颜色 */
}
.active-button::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: -3px; /* 调整下划线与文字之间的距离 */
  width: 100%;
  height: 2px; /* 下划线的高度 */
  background-color: #303133; /* 下划线颜色 */
}
.username,
.password,
.email{
  font-size: 14px;
  width: 300px;
  height: 40px;
}
.captcha{
  font-size: 14px;
  width: 190px;
  height: 40px;
}

.login-button{
  font-size: 16px;
  color: #ffffff;
  transition: color 0.3s ease,background-color 0.3s ease;
  background-color: #303133;
  border: none;
  border-radius: 0;
  height: 40px;
  width: 300px;
}
.login-button:hover{
  color: #ffffff;
  background-color: #606266;
}
.captcha-button{
  width: 90px;
  height: 40px;
  border-radius: 0;
  border: none;
  background-color: #303133;
  transition: 0.3s ease;
  color: #ffffff;
}
.captcha-button:hover{
  background-color : #606266;
  color: #ffffff;
}
:deep(.el-input__wrapper){
  border-radius: 0 !important;
  border-color: #303133 !important;
}
/* F12找到检查部分修改 */
:deep(.el-input){
  --el-border-color-hover :#303133 !important;
}
:deep(.el-input__inner:focus){
  border-color: #303133 !important;
}
:deep(.el-input__inner:after){
  border-color: #303133 !important;
}
:deep(.el-menu-item:hover){
  background-color: #F5F7FA !important;
}
:deep(.el-input__wrapper.is-focus){
  box-shadow: black;
}
:deep(.el-input){
  --el-input-focus-border: #303133;
  --el-input-focus-border-color: #303133;
}
.waiting{
  background-color: #acacac;
  cursor: not-allowed;
}
.el-button--text:not(.is-disabled):focus, .el-button--text:not(.is-disabled):hover{
  color: #606266;
  font-weight: bold;
}
</style>